<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>分类管理</title>
    <link rel="stylesheet" href="/libs/element-plus.css">
    <style>
        body {
            margin: 0;
            padding: 20px;
            background-color: #f5f7fa;
            font-family: Arial, sans-serif;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
        }
        
        .header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }
        
        .card {
            background: white;
            border-radius: 4px;
            box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
            padding: 20px;
            margin-bottom: 20px;
        }
        
        .form-item {
            margin-bottom: 15px;
        }
        
        .form-item label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        
        .form-item input, .form-item select {
            width: 100%;
            padding: 8px;
            border: 1px solid #dcdfe6;
            border-radius: 4px;
            box-sizing: border-box;
        }
        
        .btn {
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin-right: 10px;
        }
        
        .btn-primary {
            background-color: #409eff;
            color: white;
        }
        
        .btn-default {
            background-color: #ecf5ff;
            color: #409eff;
        }
        
        .btn-danger {
            background-color: #f56c6c;
            color: white;
        }
        
        .tree-node {
            padding: 8px 0;
            border-bottom: 1px solid #eee;
        }
        
        .tree-node:last-child {
            border-bottom: none;
        }
        
        .node-content {
            display: flex;
            align-items: center;
        }
        
        .node-children {
            padding-left: 30px;
            margin-top: 5px;
            border-left: 1px dashed #ddd;
        }
        
        .node-actions {
            margin-left: auto;
        }
        
        .action-btn {
            background: none;
            border: none;
            color: #409eff;
            cursor: pointer;
            margin-left: 10px;
        }
        
        .action-btn:hover {
            text-decoration: underline;
        }
        
        .loading {
            text-align: center;
            padding: 20px;
        }
        
        .spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #409eff;
            border-radius: 50%;
            width: 30px;
            height: 30px;
            animation: spin 1s linear infinite;
            margin: 0 auto;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h2>分类管理</h2>
            <button class="btn btn-primary" onclick="showCreateForm()">添加分类</button>
        </div>
        
        <div class="card">
            <div id="loadingIndicator" class="loading" style="display: none;">
                <div class="spinner"></div>
                <p>加载中...</p>
            </div>
            <div id="categoryTree">
                <!-- 分类树将通过JavaScript动态加载 -->
            </div>
        </div>
    </div>

    <!-- 分类表单弹窗 -->
    <div id="categoryModal" style="display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 1000;">
        <div style="background: white; width: 500px; margin: 100px auto; border-radius: 4px; padding: 20px;">
            <h3 id="modalTitle">添加分类</h3>
            <form id="categoryForm">
                <input type="hidden" id="categoryId">
                <div class="form-item">
                    <label for="categoryName">分类名称</label>
                    <input type="text" id="categoryName" required>
                </div>
                <div class="form-item">
                    <label for="categoryParent">父级分类</label>
                    <select id="categoryParent">
                        <option value="0">作为一级分类</option>
                    </select>
                </div>
                <div class="form-item">
                    <label for="categoryOrder">排序</label>
                    <input type="number" id="categoryOrder" value="0">
                </div>
                <div class="form-item">
                    <label for="categoryStatus">状态</label>
                    <select id="categoryStatus">
                        <option value="1">启用</option>
                        <option value="0">禁用</option>
                    </select>
                </div>
                <div style="text-align: right;">
                    <button type="button" class="btn btn-default" onclick="hideModal()">取消</button>
                    <button type="submit" class="btn btn-primary">保存</button>
                </div>
            </form>
        </div>
    </div>

    <script src="/libs/vue.global.prod.js"></script>
    <script src="/libs/element-plus.js"></script>
    
    <script>
        // 当前分类数据
        let categories = [];
        let editingCategory = null;
        
        // 页面加载完成后获取数据
        document.addEventListener('DOMContentLoaded', async function() {
            showLoading(true);
            await loadCategories();
            showLoading(false);
            renderCategoryTree();
        });
        
        // 显示/隐藏加载指示器
        function showLoading(show) {
            const loadingIndicator = document.getElementById('loadingIndicator');
            const categoryTree = document.getElementById('categoryTree');
            
            if (show) {
                loadingIndicator.style.display = 'block';
                categoryTree.style.display = 'none';
            } else {
                loadingIndicator.style.display = 'none';
                categoryTree.style.display = 'block';
            }
        }
        
        // 加载分类数据
        async function loadCategories() {
            try {
                const response = await fetch('/api/category/tree', {
                    credentials: 'include'
                });
                
                if (response.ok) {
                    const result = await response.json();
                    categories = result.data || [];
                } else {
                    console.error('获取分类数据失败:', response.status);
                    categories = []; // 确保categories是一个数组
                }
            } catch (error) {
                console.error('获取分类数据异常:', error);
                categories = []; // 确保categories是一个数组
            }
        }
        
        // 渲染分类树
        function renderCategoryTree() {
            const container = document.getElementById('categoryTree');
            container.innerHTML = '';
            
            function renderNode(category, level = 0) {
                const nodeElement = document.createElement('div');
                nodeElement.className = 'tree-node';
                
                nodeElement.innerHTML = `
                    <div class="node-content">
                        <span style="margin-left: ${level * 20}px">
                            ${category.name}
                            ${category.status == 0 ? '<span style="color: #f56c6c; font-size: 12px;">[已禁用]</span>' : ''}
                        </span>
                        <div class="node-actions">
                            <button class="action-btn" onclick="showCreateForm(${category.id})">添加子分类</button>
                            <button class="action-btn" onclick="showEditForm(${category.id})">编辑</button>
                            <button class="action-btn" onclick="deleteCategory(${category.id})">删除</button>
                        </div>
                    </div>
                `;
                
                // 渲染子分类
                if (category.children && category.children.length > 0) {
                    const childrenContainer = document.createElement('div');
                    childrenContainer.className = 'node-children';
                    
                    category.children.forEach(child => {
                        const childElement = renderNode(child, level + 1);
                        childrenContainer.appendChild(childElement);
                    });
                    
                    nodeElement.appendChild(childrenContainer);
                }
                
                return nodeElement;
            }
            
            // 只渲染顶级分类（parentId为0的分类）
            if (categories.length > 0) {
                categories.forEach(category => {
                    if (category.parentId === 0) {
                        container.appendChild(renderNode(category));
                    }
                });
            } else {
                container.innerHTML = '<p>暂无分类数据</p>';
            }
        }
        
        // 显示创建表单
        function showCreateForm(parentId = 0) {
            editingCategory = null;
            document.getElementById('modalTitle').textContent = parentId ? '添加子分类' : '添加分类';
            document.getElementById('categoryId').value = '';
            document.getElementById('categoryName').value = '';
            document.getElementById('categoryOrder').value = '0';
            document.getElementById('categoryStatus').value = '1';
            
            // 更新父级分类选项
            updateParentOptions(parentId);
            
            document.getElementById('categoryModal').style.display = 'block';
        }
        
        // 显示编辑表单
        function showEditForm(id) {
            const category = findCategoryById(categories, id);
            if (category) {
                editingCategory = category;
                document.getElementById('modalTitle').textContent = '编辑分类';
                document.getElementById('categoryId').value = category.id;
                document.getElementById('categoryName').value = category.name;
                document.getElementById('categoryOrder').value = category.orderNum || 0;
                document.getElementById('categoryStatus').value = category.status;
                
                // 更新父级分类选项
                updateParentOptions(category.parentId, category.id);
                
                document.getElementById('categoryModal').style.display = 'block';
            }
        }
        
        // 更新父级分类选项
        function updateParentOptions(selectedParentId, excludeId = null) {
            const parentSelect = document.getElementById('categoryParent');
            parentSelect.innerHTML = '<option value="0">作为一级分类</option>';
            
            function addOptions(cats, prefix = '') {
                cats.forEach(cat => {
                    // 排除自身（编辑时）
                    if (excludeId && cat.id === excludeId) return;
                    
                    const option = document.createElement('option');
                    option.value = cat.id;
                    option.textContent = prefix + cat.name;
                    option.selected = cat.id == selectedParentId;
                    parentSelect.appendChild(option);
                    
                    if (cat.children && cat.children.length > 0) {
                        addOptions(cat.children, prefix + '　');
                    }
                });
            }
            
            addOptions(categories);
        }
        
        // 查找分类通过ID
        function findCategoryById(cats, id) {
            for (const cat of cats) {
                if (cat.id === id) {
                    return cat;
                }
                if (cat.children && cat.children.length > 0) {
                    const found = findCategoryById(cat.children, id);
                    if (found) return found;
                }
            }
            return null;
        }
        
        // 隐藏模态框
        function hideModal() {
            document.getElementById('categoryModal').style.display = 'none';
        }
        
        // 删除分类
        async function deleteCategory(id) {
            if (!confirm('确定要删除该分类吗？')) {
                return;
            }
            
            try {
                const response = await fetch(`/api/category/${id}`, {
                    method: 'DELETE',
                    credentials: 'include'
                });
                
                if (response.ok) {
                    alert('删除成功');
                    showLoading(true);
                    await loadCategories();
                    showLoading(false);
                    renderCategoryTree();
                } else {
                    alert('删除失败');
                }
            } catch (error) {
                console.error('删除分类异常:', error);
                alert('删除分类时发生错误');
            }
        }
        
        // 表单提交处理
        document.getElementById('categoryForm').addEventListener('submit', async function(e) {
            e.preventDefault();
            
            const id = document.getElementById('categoryId').value;
            const name = document.getElementById('categoryName').value;
            const parentId = document.getElementById('categoryParent').value;
            const orderNum = document.getElementById('categoryOrder').value;
            const status = document.getElementById('categoryStatus').value;
            
            if (!name) {
                alert('请输入分类名称');
                return;
            }
            
            const categoryData = {
                name,
                parentId: parseInt(parentId),
                orderNum: parseInt(orderNum),
                status: parseInt(status)
            };
            
            try {
                let response;
                if (editingCategory) {
                    // 更新分类
                    response = await fetch(`/api/category/${id}`, {
                        method: 'PUT',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(categoryData),
                        credentials: 'include'
                    });
                } else {
                    // 创建分类
                    response = await fetch('/api/category', {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify(categoryData),
                        credentials: 'include'
                    });
                }
                
                if (response.ok) {
                    alert(editingCategory ? '更新成功' : '创建成功');
                    hideModal();
                    showLoading(true);
                    await loadCategories();
                    showLoading(false);
                    renderCategoryTree();
                } else {
                    alert(editingCategory ? '更新失败' : '创建失败');
                }
            } catch (error) {
                console.error('保存分类异常:', error);
                alert('保存分类时发生错误');
            }
        });
    </script>
</body>
</html>